<?php
// +----------------------------------------------------------------------
// | Description: 加密token操作类
// +----------------------------------------------------------------------
// | Author: linchuangbin <linchuangbin@honraytech.com>
// +----------------------------------------------------------------------

namespace app\v2\model;

use think\Db;

use think\Model;
class Token extends Model 
{	
    
    /**
     *  默认时间戳是字段  creat_time
     *  默认时间戳是格式  datetime
     */
	// protected $name = 'user_token';
 //    protected $createTime = 'time';
 //    protected $updateTime = "time";
	// protected $autoWriteTimestamp = 'datetime';

    function apiEncode($uid,$auth_key = 'qhdkb')
    {
       $business_connect = Db::connect('db_business')->table('qh_user_token');

       $tokenRes = $business_connect->where(array('uid'=>$uid))->find();
       $time = time();
       $token = md5($uid.$time.$auth_key);
       $data = array();
       $data['token'] = $token;
       $data['uid'] = $uid;
       $data['time'] = date('Y-m-d H:i:s',time());

       $business_connect = Db::connect('db_business')->table('qh_user_token');
       if(!$tokenRes){

         $business_toke = $business_connect->insert($data);
       }else{
         $business_toke = $business_connect->where(array('uid'=>$uid))->update($data);
       }
       
       if(!$business_toke){
        return false;
       }else{
        return $token;
       }
       
    }


    function apiDecode($token)
    {
     
        $tokenRes = $this->where(array('token'=>$token))->find();
        $tokenRes = $tokenRes?$tokenRes->toArray():array();
        if(!$tokenRes || !$tokenRes['uid']){
            $this->error = "无效的token" ;
            return false;
        }
        $tokenRes['time'] = strtotime($tokenRes['time']);
        /* 一个月有效期 */
        if(time() - $tokenRes['time'] >= 3600*24*30){
            $this->error = "token过期" ;
            return false;
        }

        $status =Db::name('user')->where(array('uid'=>$tokenRes['uid']))->value('status');

        if(!isset($status)){
            $this->error = "账户不存在" ;
            return false;
        }elseif($status == 0){
            $this->error = "账户已被禁用" ;
            return false;
        }else{
            
        }
        return $tokenRes['uid'];

    }


}